package net.yambal.android.google_calender;

import java.util.ArrayList;
import java.util.List;

import android.content.Context;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import android.widget.CheckBox;
import android.widget.CompoundButton;
import android.widget.CompoundButton.OnCheckedChangeListener;

public class ArrayAdapterGoogleCalenders extends ArrayAdapter<GoogleCalender> {
	private int _textViewResourceId;
	private List<GoogleCalender> _google_calenders;
	private LayoutInflater _inflater;
	private ListenerArrayAdapterGoogleCalender _listener;
	
	public ArrayAdapterGoogleCalenders(Context context, int textViewResourceId, List<GoogleCalender> google_calenders, ListenerArrayAdapterGoogleCalender listener) {
		super(context, textViewResourceId, google_calenders);
		_textViewResourceId = textViewResourceId;
		_google_calenders = google_calenders;
		_inflater = (LayoutInflater)context.getSystemService(
				Context.LAYOUT_INFLATER_SERVICE
		);
		_listener = listener;
	}
	
	@Override
	public View getView(int position, View convertView, ViewGroup parent){
		if(convertView == null){
			convertView = _inflater.inflate(_textViewResourceId, null);
		}
		final GoogleCalender google_calender = _google_calenders.get(position);
		if(google_calender != null){
			CheckBox check_box = (CheckBox)convertView.findViewWithTag("checkBoxCalenderSelector");
			check_box.setText(google_calender.displayName);
			final int p = position;
	        check_box.setOnCheckedChangeListener(new OnCheckedChangeListener(){
				@Override
				public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
					google_calender.my_selected = isChecked;
					_google_calenders.set(p, google_calender);
					onMySelectedChange();
		        }
			});
	        check_box.setChecked(google_calender.my_selected);
		}
		return convertView;
	}
	
	private void onMySelectedChange(){
		List<String> selected_ids = new ArrayList<String>();
		for(int i = 0; i < _google_calenders.size(); i++){
			GoogleCalender calender = _google_calenders.get(i);
			if(calender.my_selected){
				selected_ids.add(calender._id);
			}
		}
		_listener.onMySelectedChange(selected_ids);
	}
	
	@Override
    public GoogleCalender getItem(int position) {
      return _google_calenders.get(position);
    }
	
	@Override
    public int getCount() {
      return _google_calenders.size();
    }
	
	@Override
    public long getItemId(int position) {
      return position;
    }
}
